package me.qingy.core.service.impl;

import me.qingy.common.constant.ShiroConstants;
import me.qingy.core.entity.UserOnline;
import me.qingy.core.mapper.UserOnlineMapper;
import me.qingy.core.service.UserOnlineService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Date;
import java.util.Deque;
import java.util.List;

/**
 * <p>
 * 在线用户记录 服务实现类
 * </p>
 *
 * @author qingy
 * @since 2021-04-28
 */
@Service
public class UserOnlineServiceImpl extends ServiceImpl<UserOnlineMapper, UserOnline> implements UserOnlineService {

    @Autowired
    private EhCacheManager ehCacheManager;

    @Override
    public List<UserOnline> selectOnlineByExpired(Date expiredDate) {
        return this.baseMapper.selectOnlineByExpired(expiredDate);
    }

    @Override
    public void batchDeleteOnline(List<String> needOfflineIdList) {
        this.baseMapper.deleteBatchIds(needOfflineIdList);
    }

    @Override
    public void removeUserCache(String loginName, String sessionId) {
        Cache<String, Deque<Serializable>> cache = ehCacheManager.getCache(ShiroConstants.SYS_USERCACHE);
        Deque<Serializable> deque = cache.get(loginName);
        if (deque == null || deque.size() == 0) {
            return;
        }
        deque.remove(sessionId);
    }
}
